<script setup lang="ts">
import { graphic } from 'echarts'
import useEcharts, { type EChartsOption } from '~/composables/chart'

import BlockHead from './block-head.vue'

import defaults from './default-chart-option'
import icon from './item-icon-2.png'

import ItemSummaryInfo from './item-summary-info.vue'

defineOptions({
  name: 'ItemTwo',
})

const props = defineProps<{
  total: string | number
  data1: { name: string, value: string | number }[]
  data2: { name: string, value: string | number }[]
}>()

const { chartRef, setOption } = useEcharts()

const option = computed<EChartsOption>(() => {
  return {
    tooltip: { ...defaults.tooltip, axisPointer: { type: 'cross' } },
    grid: { ...defaults.grid, top: 100, right: 50, left: 30 },
    legend: { ...defaults.legend, data: ['本期值', '同期值'], top: 70 },
    xAxis: {
      type: 'category',
      data: props.data1.map(item => item.name),
      axisLine: { show: false },
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      boundaryGap: false,
    },
    series: [
      {
        name: '本期值',
        type: 'line',
        data: props.data1.map(v => v.value),
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 5,
        itemStyle: {
          color: 'rgba(46, 137, 250, 1)',
        },
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(46, 137, 250, 0.5)' },
            { offset: 1, color: 'rgba(46, 137, 250, 0)' },
          ]),
        },
      },
      {
        name: '同期值',
        type: 'line',
        data: props.data2.map(v => v.value),
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 5,
        itemStyle: {
          color: 'rgba(94, 214, 255, 1)',
        },
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(94, 214, 255, 0.5)' },
            { offset: 1, color: 'rgba(94, 214, 255, 0)' },
          ]),
        },
      },
    ],
  }
})

onMounted(() => {
  setOption(option.value)
})

watch([chartRef, option], () => {
  setOption(option.value)
})
</script>

<template>
  <div class="flex flex-col">
    <BlockHead title="用电趋势分析" />
    <div class="block-body h-70 w-full flex-auto items-center">
      <div class="relative h-full w-full">
        <div v-if="(data1 && data1.length > 0) || (data2 && data2.length > 0)" ref="chartRef" style="width:100%;height:100%" />
        <div v-else class="absolute left-0 right-0 mt-40 text-center text-sm opacity-50">
          暂无数据
        </div>
        <ItemSummaryInfo
          class="absolute left-4 right-4 top-3"
          :icon="icon"
          :data="{
            title: '年用电量',
            value: total,
            unit: 'kwh',
          }"
        />
      </div>
    </div>
  </div>
</template>
